package cxm.mmp.aud;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;

import cxm.lib.util.MyLog;

public class FileRecordingReader implements IRecordingSource {
	File file = null;
	DataInputStream dis = null;

	public FileRecordingReader(File file) {
		this.file = file;
	}

	public int onRecordStart() {
		try {
			this.dis = new DataInputStream(new BufferedInputStream(
					new FileInputStream(this.file)));
			return 0;
		} catch (Exception e) {
			MyLog.Log(MyLog.Level.Error, "Cannot create stream for reading: " + e);
			return -1;
		}
	}
	
	public int onRecordData(byte []data, int start, int num) {
		int i = 0;
		for (i = 0; i < num; i++) {
			try {
				data[start + i] = this.dis.readByte();
			} catch (Exception e) {
				MyLog.Log(MyLog.Level.Error, "Cannot read data count at "
					+ i + ": " + e);
				break;
			}
		}

		return i;
	}
	
	public int onRecordStop() {
		if (null != this.dis)
			try {
				this.dis.close();
			} catch (Exception e) {
				MyLog.Log(MyLog.Level.Error, "Cannot close file: " + e);
			}
		return 0;
	}
	
	public int onRecordError(IRecordingSource.RecordError error, int errno) {
		MyLog.Log(MyLog.Level.Error, "On Recording error type: " + error.toString() +
				" error number: " + errno);
		return 0;
	}
}
